package com.wangsh.webforward.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

/**
 * poi相关的工具类
 * 
 * @author
 */
public class POIUtil
{
	private FileUtil fileUtil = new FileUtil();

	/**
	 * 读取文件内容
	 * 
	 * @param path 文件的完整路径
	 */
	public List<Map<String, String>> readFileCsv(String path)
	{
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Map<String, String> map = null;
		if (path.endsWith(".csv"))
		{
			try
			{
				// 创建CSV读对象
				//CsvReader csvReader = new CsvReader(path, ',', Charset.forName("GBK"));
				CsvReader csvReader = new CsvReader(new FileInputStream(new File(path)), Charset.forName("GBK"));
				// 跳过表头
				csvReader.readHeaders();
				String[] headers = csvReader.getHeaders();
				while (csvReader.readRecord())
				{
					map = new LinkedHashMap<String, String>();
					for (int i = 0; i < headers.length; i++)
					{
						map.put(headers[i], csvReader.get(headers[i]));
					}
					list.add(map);
				}
			} catch (FileNotFoundException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}

	/**
	 * 写入csv文件的工具类
	 * 
	 * @param path要写入文件的路径
	 * @param headerList   标题信息,每个字段都代表第一行的列
	 * @param contentList  内容,外部的list代表一行,内圈的list代表每行的每一列
	 * 
	 */
	public void writeFileCsv(String path, List<String> headerList, List<List<String>> contentList)
	{
		CsvWriter csvWriter = new CsvWriter(path, ',', Charset.forName("GBK"));
		try
		{
			File file = new File(path);
			if (!file.exists())
			{
				if (!file.getParentFile().exists())
				{
					file.getParentFile().mkdirs();
				}
			}
			file.createNewFile();
			if (headerList != null && headerList.size() > 0)
			{
				String[] header = headerList.toArray(new String[0]);
				csvWriter.writeRecord(header);
			}
			if (contentList != null && contentList.size() > 0)
			{
				for (List<String> listContent : contentList)
				{
					if (listContent != null && listContent.size() > 0)
					{
						String[] array = listContent.toArray(new String[0]);
						csvWriter.writeRecord(array);
					}

				}
			}

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally
		{
			csvWriter.close();
		}
	}
}
